package com.example.completionservice.aatest2;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/** 对CompletionService封装，实现快速处理业务任务并汇总结果 https://blog.csdn.net/zhaozhenzuo/article/details/52138140
 *
 * @date: 2020/1/17  11:19
 **/
@RestController
public class Test2Controller {
    private static final Logger logger = LoggerFactory.getLogger(com.example.completionservice.controller.CompletionServiceController.class);

    //多线程异步并发接口
    @GetMapping("/test2")
    public String asyncExec() {
        long start = System.currentTimeMillis();

        ExecutorService executorService = Executors.newFixedThreadPool(50);
        final QuickProcessByNotify<String, Long>
                quickProcess = new QuickProcessByNotify<String, Long>(executorService, new QuickTaskResultHandler<String, Long>());
        long allCount = quickProcess.processByCallBack(
                new QuickBizProcessCallbak() {
                    //QuickBizProcessCallbak是业务处理回调接口，业务方实现此接口
                    public void doBiz() {
                        for (int i = 0; i < 10; i++) {
                            quickProcess.submit(getTask());
                        }
                    }
                }
        );
        logger.info("--->allCount: " + allCount);

        logger.info("异步总共耗时：" + (System.currentTimeMillis() - start));
        return "ok";
    }

    // 得到一个任务
    public Callable<String> getTask() {
        Callable<String> task = new Callable<String>() {
            //一定要提交业务任务到快速处理器
            public String call() throws Exception {
                int i = 1;
                int j = 0;
                int sum = i + j;
//                logger.info(sum + "\t");
                return sum + "";
            }
        };
        return task;
    }

}
